import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { message } from '@maycur/antd5'
import './style/ColumnSetPanelItem.less';
let prefix = 'mctable';

function ColumnSetPanelItem (props) {
    const { canDrag, endDrag, movePanel, panel, index, id, checked, onCheck, canCancel } = props;
    const ref = useRef(null);

    const [, drop] = useDrop({
        accept: 'column',
        hover(item, monitor) {
            if (!ref.current) {
                return;
            }
            const dragIndex = item.index;
            const hoverIndex = index;
            if (dragIndex === hoverIndex) {
                return;
            }
            const hoverBoundingRect = ref.current.getBoundingClientRect();
            const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
            const clientOffset = monitor.getClientOffset();

            const hoverClientY = clientOffset.y - hoverBoundingRect.top;
            if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
                return;
            }
            // Dragging upwards
            if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
                return;
            }
            movePanel(dragIndex, hoverIndex);
            item.index = hoverIndex;
        }
    });

    const [{ isDragging }, drag] = useDrag({
        item: { type: 'column', index, id },
        canDrag: monitor => {
            return !!canDrag;
        },
        collect: monitor => ({
            isDragging: monitor.isDragging()
        }),
        end: (item, monitor) => {
            endDrag();
        }
    });

    const _onCheck = () => {
        if (typeof onCheck === 'function') {
            if (!canCancel && checked) {
                message.warning('需至少选择一个字段展示')
                return;
            }
            onCheck(index, !checked);
        }
    }

    const opacity = isDragging ? 0 : 1;
   
    drag(drop(ref));
    
    return (
        <div 
            className={`${prefix}-column-set-panel-item-wrapper ${checked ? 'checked' : ''}`} 
            style={{ opacity }} 
            onClick={_onCheck}
            ref={ref}
        >
            <div>
                <span className={`${prefix}-fm ${prefix}-fm-list`} style={{cursor: 'move'}} />
                <span style={{marginLeft: 10}}>
                    {
                        (typeof panel.label === 'string' || React.isValidElement(panel.label)) ? 
                            panel.label: 
                            null
                    }
                </span>
            </div>
            <span className={`${prefix}-fm ${prefix}-fm-check`} />
        </div>
    );
}

export default ColumnSetPanelItem;
